<script setup>
import { ref } from "vue";
import articleApi from "@/api/article";
//dialog弹出框
const dialogVisible = ref(false);


/* 组件对外暴露一个方法open,基于open方法，区分是添加还是修改
open({}) ==> 表单无需渲染，说明是添加
open({id,cate_name,...}) ==> 表单需要渲染是，说明是编辑
open 调用之后，需要打开弹窗
*/
const open = (row) => {
  console.log(row);
  dialogVisible.value = true;
  formModel.value = { ...row }; //通过展开运算符，把里面的数据全部给这个formModel表单
};

const formModel = ref({
  cate_name: "",
  cate_alias: "",
});

//如何向我们组件外部暴露方法
defineExpose({
  open,
});

//弹窗输入的文本校验规则
const rules = {
  cate_name: [
    {
      required: true,
      message: "请输入分类名称",
      trigger: "blur",
    },
    {
      pattern: /^\S{1,10}$/,
      message: "分类名称必须是1到10位的非空字符",
      trigger: "blur",
    },
  ],
  cate_alias: [
    {
      required: true,
      message: "请输入分类别名",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: "分类别名必须是1-15位的字母或数字",
      trigger: "blur",
    },
  ],
};

const formRef = ref();//绑定dom
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate();
  const isEdit = formModel.value.id;//看看你是是否是编辑还是添加
  if(isEdit){
    await articleApi.editArticle(formModel.value)
  }else {
    await articleApi.addArticle(formModel.value)
  }
  ElMessage.success({
      type:'success',
      message:formModel.id ? '编辑成功':'添加成功'
    });
  dialogVisible.value = false;//关闭弹层
  //通知老爹，刷新列表数据
  emit('success')//通知父组件消息，让父组件去刷新页面列表数据，暂时不需要传递任何数据
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="30%"
    center
  >
    <el-form
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
      ref="formRef"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModel.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formModel.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>